package com.matrix.draft.juc.day7;

import java.util.concurrent.locks.StampedLock;

/**
 * 时间戳锁
 */
public class TestStampedLock {
    public static void main(String[] args) {
    }
}

class DataCache {

    private String cache = "123456789";

    private StampedLock lock = new StampedLock();

    // 读
    private String readCache() {
        // 先尝试不加锁,得到一个stamp
        long stamp = lock.tryOptimisticRead();
        // 正真要读的时候, 验证刚刚的stamp是否有效
        if (lock.validate(stamp)) {
            return cache;
        }
        // 如果stamp失效, 就加读锁
        try {
            stamp = lock.readLock();
            return cache;
        } finally {
            lock.unlockRead(stamp);
        }
    }

    // 写
    public void writeCache(String newCache){
        long stamp = lock.writeLock();
        cache = newCache;
        lock.unlockWrite(stamp);
    }

}